// pages/myself/merchant/MerchantCouponDetails.js
var Zan = require('../../../dist/index.js');
var QQMapWX = require('../../../utils/qqmap-wx-jssdk.min.js');
let WxNotificationCenter = require('../../../utils/WxNotificationCenter.js');
let network = null;
let utils = null;
let api = null;
const app = getApp();
let constants = null;
Page(Object.assign({}, Zan.TopTips, Zan.Toast, {

  /**
   * 页面的初始数据
   */
  data: {
    couponId: '',
    lat: '',
    lng: '',
    coupon: {},
    stores: [],
    users: [],
    users2: []
  },

  /** 
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    network = new app.NetWorkUtils();
    utils = new app.Utils();
    api = new app.Api();
    WxNotificationCenter.addNotification("RefreshDetailsCoupon", this.refreshDetailsCoupon, this)
    this.setData({
      couponId: options.couponId
    })

    constants = new app.Constants();
    var that = this;
    wx.getLocation({
      type: 'wgs84',
      success: function (res) {
        let latitude = res.latitude
        let longitude = res.longitude
        wx.request({
          url: `https://apis.map.qq.com/ws/geocoder/v1/?location=${latitude},${longitude}&key=${constants.key}`,
          success: res => {
            console.log(res);
            let location = res.data.result.ad_info;
            that.setData({
              lng: res.data.result.location.lng,
              lat: res.data.result.location.lat,
              province: location.province,
              city: location.city,
              district: location.district
              // region: [location.province, location.city, location.district]
            })
            that.onPullDownRefresh()
          }
        })
      }
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    WxNotificationCenter.removeNotification("RefreshDetailsCoupon", this);
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    wx.stopPullDownRefresh();
    this.setData({
      stores: [],
      users: [],
      users2: []
    })
    network._post_json(this, api.couponDetails, { couponId: this.data.couponId, lat: this.data.lat, lng: this.data.lng }, success);

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    var that = this;
    return {
      title: that.data.coupon.name,
      path: '/pages/discount/CouponDetails?couponId=' + that.data.coupon.id,
      success: function (res) {
      },
      fail: function (res) {
        // 转发失败
      }
    }
  },
  
  moreCoupon: function (e) {
    var brandId = e.currentTarget.dataset.id;
    var status = e.currentTarget.dataset.status;
    var name = e.currentTarget.dataset.name;
    wx.navigateTo({
      url: '/pages/discount/BrandCoupon' + '?brandId=' + brandId + '&status=' + status + '&name=' + name,
    })
  },
  goMap: function (e) {
    //114.35663,30.52636
    var lat = e.currentTarget.dataset.lat;
    var lng = e.currentTarget.dataset.lng;
    wx.openLocation({
      type: 'wgs84 ',
      latitude: lat,
      longitude: lng,
      scale: 18
    });
  },
  goCouponUser: function (e) {
    var id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: '/pages/discount/CouponUser' + '?couponId=' + id,
    })
  },
  goCouponUser2: function (e) {
    var id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: '/pages/discount/CouponUser2' + '?couponId=' + id,
    })
  },
  /**
 * 上下架
 */
  release: function (e) {
    var status = e.currentTarget.dataset.status;
    var couponId = e.currentTarget.dataset.couponid;
    var brandId = e.currentTarget.dataset.brandid;
    if (status == 1) {
      network._post_json(this, api.onDownCoupon, { brandId: brandId, couponId: couponId, status: 0 }, redownSuccess)
    } else {
      network._post_json(this, api.onDownCoupon, { brandId: brandId, couponId: couponId, status: 1 }, reonSuccess);
    }
  },
  /**
   * 删除
   */
  del: function (e) {
    var couponId = e.currentTarget.dataset.couponid;
    var that = this
    wx.showModal({
      title: '提示',
      content: '确定删除吗？',
      success: function (res) {
        if (res.confirm) {
          console.log('用户点击确定')
          network._post_json(that, api.delCoupon, { couponId: couponId }, delSuccess);
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  },
  /**
   * 编辑
   */
  edit: function (e) {
    var status = e.currentTarget.dataset.status;
    var couponId = e.currentTarget.dataset.couponid;
    var brandId = e.currentTarget.dataset.brandid;
    if (couponId && status == 0) {
      if (utils.canTap(e)) {
        wx.navigateTo({
          url: '/pages/myself/send/EditCoupon?couponId=' + couponId + '&status=' + status + '&BrandId=' + brandId + '&editgotype=1'
        })
      }
    }

  },
  refreshDetailsCoupon:function(){
    this.setData({
      stores: [],
      users: [],
      users2: []
    })
    network._post_json(this, api.couponDetails, { couponId: this.data.couponId, lat: this.data.lat, lng: this.data.lng }, success);
  }

}))
var success = function (that, res) {
  res.data.data.startTime = utils.formatDate02(new Date(res.data.data.startTime))
  res.data.data.endTime = utils.formatDate02(new Date(res.data.data.endTime))
  for (var i = 0; i < res.data.data.stores.length;i++){
    res.data.data.stores[i].openTime = utils.formatDate03(new Date(res.data.data.stores[i].openTime))
    res.data.data.stores[i].closeTime = utils.formatDate03(new Date(res.data.data.stores[i].closeTime))
  }
  if (res.data.data) {
    that.setData({
      coupon: res.data.data,
      stores: that.data.stores.concat(res.data.data.stores),
      users: that.data.users.concat(res.data.data.users).slice(0, 3),
      users2: that.data.users2.concat(res.data.data.users2).slice(0, 3)
    })
  }
}
var redownSuccess = function(that,res){
  WxNotificationCenter.postNotificationName("RefreshDownCoupon", true);
  that.showZanToast('下架成功！');
  wx.navigateBack();
}
var reonSuccess = function(that,res){
  WxNotificationCenter.postNotificationName("RefreshOnCoupon",1);
  that.showZanToast('上架成功！');
  wx.navigateBack();
}
var delSuccess = function(that,res){
  WxNotificationCenter.postNotificationName("RefreshOnCoupon",2);
  that.showZanToast('优惠券删除成功！');
  wx.navigateBack();
}